package com.zjdiepu.www.manage.api.dh;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.InsteadPaymentStatus;
import com.zjdiepu.www.base.enums.type.LoanBankType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.consts.ExcelTitleRowConsts;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.ExcelUtil;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.config.FileProperty;
import com.zjdiepu.www.ibiz.dh.IDhInsteadPaymentApplyService;
import com.zjdiepu.www.ibiz.dh.IDhInsteadPaymentBatchService;
import com.zjdiepu.www.ibiz.dh.IDhInsteadPaymentService;
import com.zjdiepu.www.ibiz.dz.IDzLoanMiddleBankService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.model.dh.dto.DhInsteadPayment;
import com.zjdiepu.www.model.dh.dto.DhInsteadPaymentApply;
import com.zjdiepu.www.model.dh.dto.DhInsteadPaymentBatch;
import com.zjdiepu.www.model.dh.ext.DhInsteadPaymentExt;
import com.zjdiepu.www.model.dz.dto.DzLoanMiddleBank;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.ext.YwBusinessExt;

/**
 * Controller层<br/>
 * @author zhangzhengjian<br/>
 * 代偿客户
 * @time 2017年05月22日 16时22分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "DhInsteadPaymentController", produces="application/json;charset=UTF-8")
@Api(tags = {""}, produces="application/json;charset=UTF-8")
public class DhInsteadPaymentController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private IDhInsteadPaymentService dhInsteadPaymentService;
    @Resource
	private FileProperty fileProperty;
    @Resource
    private IDhInsteadPaymentApplyService dhInsteadPaymentApplyService;
    @Resource
    private IDhInsteadPaymentBatchService dhInsteadPaymentBatchService;
    
    @Resource
	private IDzLoanMiddleBankService dzLoanMiddleBankService;
    @Resource
	private IYwBusinessService ywBusinessService;

    /**
     * @author zhangzhengjian <br/>
     * @Title: batchImport  <br/>
     * @Description: 导入代偿客户 <br/>
     * @param name
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "导入代偿客户", response = Boolean.class, httpMethod="POST", tags={"导入"})
    @RequestMapping(value = "batchImport", method = RequestMethod.POST)
    public ApiResponse batchImport(String name,String bankCode){
    	if(name ==null || "".equals(name)){
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	if(bankCode!=null && !bankCode.equals(LoanBankType.GONG_SHANG_YIN_HANG.getCode())){
//    		return ApiResponse.fail(ResultFlagType.PLEASE_CHOOSE_COLLECT_MODEL);
    	}
    	String uuid=UUIDFactory.getUUID();
    	URL xmlpath = this.getClass().getClassLoader().getResource("");
		String pathTo="";
        try {
			pathTo=String.valueOf(xmlpath)+new String(fileProperty.getUploadPath().getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        if(pathTo.contains("file:/")){
        	pathTo=pathTo.substring(6,pathTo.length());
        }
    	
    	List<List<String>> list=ExcelUtil.getExcelContent(pathTo+name,20);
    	List<DhInsteadPayment> listPayment= new ArrayList<DhInsteadPayment>();
    	List<List<String>> listError=new ArrayList<List<String>>();
    	DhInsteadPayment dhInsteadPayment=null;
    	String cardNo="";
    	if(list ==null){
    		return ApiResponse.fail(ResultFlagType.MISSING);
    	}
    	for(int i=1;i<list.size();i++){
			for(int j=list.size()-1;j>i;j--){ 
				if(list.get(j).get(2).equals(list.get(i).get(2))){
					listError.add(list.get(j));
				}
			}
		}
    	List<String> paymentList=CollectionInitUtil.emptyList();
    	Integer current = (int)(System.currentTimeMillis() / 1000);
    	AbstractSysUser currentUser = getCurrentUser();
    	YwBusinessExt ywbusinessExt=null;
    	DzLoanMiddleBank dzLoanMiddleBank=null;
    	String custNo="";
    	for(int i=1;i<list.size();i++){
    		paymentList=list.get(i);
    		dhInsteadPayment=new DhInsteadPayment();
    		
    		ywbusinessExt= new YwBusinessExt();
    		custNo=paymentList.get(4);
			ywbusinessExt.setCustomerNo(custNo.contains(".")?custNo.substring(0,custNo.indexOf(".")):custNo);
    		List<YwBusiness> listLoanAfter=ywBusinessService.selectByExt(ywbusinessExt);
    		if(listLoanAfter.size()>1){
    			paymentList.add("该客户有多笔订单，不支持导入");
				listError.add(paymentList);
				continue;
			}
    		cardNo=paymentList.get(2);
    		cardNo=cardNo.contains(".")?cardNo.substring(0,cardNo.indexOf(".")):cardNo;
    		if(listLoanAfter.isEmpty()){
    			paymentList.add("该客户在系统中查不到订单");
    			listError.add(paymentList);
    		}else{
    			if(StringUtils.isEmpty(paymentList.get(0))) continue;
    			dhInsteadPayment.setBusiId(listLoanAfter.get(0).getId());
    			dhInsteadPayment.setCusId(listLoanAfter.get(0).getCustomerId());
    			dhInsteadPayment.setBatchId(uuid);
    			dhInsteadPayment.setId(UUIDFactory.getUUID());
    			dhInsteadPayment.setCardNo(cardNo);
    			dhInsteadPayment.setCusName(paymentList.get(3));
    			dhInsteadPayment.setCusNo(paymentList.get(4));
    			dhInsteadPayment.setBalance(Double.parseDouble(paymentList.get(5)));
    			dhInsteadPayment.setAmountLowest(Double.parseDouble(paymentList.get(6)));
    			dhInsteadPayment.setPrincipleOverdraft(Double.parseDouble(paymentList.get(7)));
    			dhInsteadPayment.setInterestOverdraft(Double.parseDouble(paymentList.get(8)));
    			dhInsteadPayment.setAccreditTotal(Double.parseDouble(paymentList.get(9)));
    			dhInsteadPayment.setDateNumOverdue((int)Double.parseDouble(paymentList.get(10)));
    			dhInsteadPayment.setNumContinuous((int)Double.parseDouble(paymentList.get(11)));
    			dhInsteadPayment.setStage(paymentList.get(12));
    			dzLoanMiddleBank= new DzLoanMiddleBank();
				dzLoanMiddleBank.setBusiId(listLoanAfter.get(0).getId());
				dzLoanMiddleBank=dzLoanMiddleBankService.selectRefined(dzLoanMiddleBank);
				//如果银行登记的卡号和EXCEL中的卡号不一样，修改贷中银行信息表中的卡号
				if(dzLoanMiddleBank !=null){
					if(!dzLoanMiddleBank.getCardnoRefund().equals(cardNo)){
						DzLoanMiddleBank dzLoanMiddleBank1= new DzLoanMiddleBank();
						dzLoanMiddleBank1.setId(dzLoanMiddleBank.getId());
						dzLoanMiddleBank1.setCardnoRefund(cardNo);
						dzLoanMiddleBank1.setRemarks("原先卡号:"+dzLoanMiddleBank.getCardnoRefund()+"，现在卡号:"+cardNo);
						dzLoanMiddleBankService.saveUpdateAndDelete(dzLoanMiddleBank1, OperateType.edit);
					}
				}
    			dhInsteadPayment.setDpStatus(1);
    			dhInsteadPayment.setTypeData(1);
    			dhInsteadPayment.setCreated(current);
    			dhInsteadPayment.setCreator(currentUser.getId());
    			dhInsteadPayment.setCreatorName(currentUser.getName());
    			dhInsteadPayment.setModified(current);
    			dhInsteadPayment.setModifier(currentUser.getId());
    			dhInsteadPayment.setModifierName(currentUser.getName());
    			dhInsteadPayment.setStatusInstead(InsteadPaymentStatus.NOAPPLY.getCode());
    			dhInsteadPayment.setDateInstead(new Date());
    			listPayment.add(dhInsteadPayment);
    		}
    	}
//    	ExcelUtil.importExcel("D:/待垫资客户错误信息.xlsx", ExcelTitleRowConsts.EXCELTYPE1, listError, getTitleRow());
    	logger.debug("导入错误数据到EXCEL成功！");
    	if(listPayment==null || listPayment.size()<=0){
    		return ApiResponse.fail(ResultFlagType.MISSING);
    	}
    	dhInsteadPaymentService.insertBatch(listPayment);
    	DhInsteadPaymentBatch dhInsteadPaymentBatch= new DhInsteadPaymentBatch();
    	dhInsteadPaymentBatch.setBank(bankCode);
    	dhInsteadPaymentBatch.setId(uuid);
    	dhInsteadPaymentBatch.setDateInstead(new Date());
    	dhInsteadPaymentBatch.setNumInstead(listPayment.size());
    	dhInsteadPaymentBatchService.saveUpdateAndDelete(dhInsteadPaymentBatch, OperateType.add);
    	if(listError!=null && listError.size()>0){
			ExcelUtil.importExcel(pathTo+"待垫资客户错误信息.xlsx", ExcelTitleRowConsts.EXCELTYPE1, listError, getTitleRow());
			return ApiResponse.fail(111111,"部分客户导入未成功，具体原因请查询 "+pathTo+"银行错误信息.xlsx");
		}
    	
    	return ApiResponse.success(true);
    }
    
    private List<String> getTitleRow() {
    	List<String> arr1= new ArrayList<String>();
		arr1.add(ExcelTitleRowConsts.EXCELROW50);
		arr1.add(ExcelTitleRowConsts.EXCELROW51);
		arr1.add(ExcelTitleRowConsts.EXCELROW52);
		arr1.add(ExcelTitleRowConsts.EXCELROW53);
		arr1.add(ExcelTitleRowConsts.EXCELROW54);
		arr1.add(ExcelTitleRowConsts.EXCELROW55);
		arr1.add(ExcelTitleRowConsts.EXCELROW56);
		arr1.add(ExcelTitleRowConsts.EXCELROW57);
		arr1.add(ExcelTitleRowConsts.EXCELROW58);
		arr1.add(ExcelTitleRowConsts.EXCELROW59);
		arr1.add(ExcelTitleRowConsts.EXCELROW60);
		arr1.add(ExcelTitleRowConsts.EXCELROW61);
		arr1.add(ExcelTitleRowConsts.EXCELROW62);
		arr1.add(ExcelTitleRowConsts.EXCELROW63);
		arr1.add(ExcelTitleRowConsts.EXCELROW64);
		arr1.add(ExcelTitleRowConsts.EXCELROW65);
		arr1.add(ExcelTitleRowConsts.EXCELROW66);
		arr1.add(ExcelTitleRowConsts.EXCELROW67);
		arr1.add(ExcelTitleRowConsts.EXCELROW68);
		arr1.add(ExcelTitleRowConsts.EXCELROW69);
		return arr1;
	}

	@ApiOperation(value = "预览", response = Boolean.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "preview", method = RequestMethod.POST)
    public ApiResponse preview(String name,boolean initFlag,String bankCode){
    	if(initFlag==true){
			return ApiResponse.success(CollectionInitUtil.emptyList());
		}
    	if(bankCode!=null && !bankCode.equals(LoanBankType.GONG_SHANG_YIN_HANG.getCode())){
//    		return ApiResponse.fail(ResultFlagType.PLEASE_CHOOSE_COLLECT_MODEL);
    	}
    	if(name ==null || "".equals(name)){
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	URL xmlpath = this.getClass().getClassLoader().getResource("");
		String pathTo="";
        try {
			pathTo=String.valueOf(xmlpath)+new String(fileProperty.getUploadPath().getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        if(pathTo.contains("file:/")){
        	pathTo=pathTo.substring(6,pathTo.length());
        }
    	
    	
    	List<List<String>> list=ExcelUtil.getExcelContent(pathTo+name,20);
    	DhInsteadPayment dhInsteadPayment=null;
		List<DhInsteadPayment> listDhOverdue=new ArrayList<DhInsteadPayment>();
		String cardNo="";
		List<String> paymentList=CollectionInitUtil.emptyList();
    	YwBusinessExt ywbusinessExt=null;
    	String custNo="";
		for(int i=1;i<list.size();i++){
			paymentList=list.get(i);
			dhInsteadPayment=new DhInsteadPayment();
    		ywbusinessExt= new YwBusinessExt();
    		custNo=paymentList.get(4);
			ywbusinessExt.setCustomerNo(custNo.contains(".")?custNo.substring(0,custNo.indexOf(".")):custNo);
    		List<YwBusiness> listLoanAfter=ywBusinessService.selectByExt(ywbusinessExt);
    		cardNo=paymentList.get(2);
    		cardNo=cardNo.contains(".")?cardNo.substring(0,cardNo.indexOf(".")):cardNo;
    		if(listLoanAfter.isEmpty()){
    			
    		}else{
    			if(StringUtils.isEmpty(paymentList.get(0))) continue;
    			dhInsteadPayment.setBusiId(listLoanAfter.get(0).getId());
    			dhInsteadPayment.setCusId(listLoanAfter.get(0).getCustomerId());
    			dhInsteadPayment.setId(UUIDFactory.getUUID());
    			dhInsteadPayment.setCardNo(cardNo);
    			dhInsteadPayment.setCusName(paymentList.get(3));
    			dhInsteadPayment.setCusNo(paymentList.get(4));
    			dhInsteadPayment.setBalance(Double.parseDouble(paymentList.get(5)));
    			dhInsteadPayment.setAmountLowest(Double.parseDouble(paymentList.get(6)));
    			dhInsteadPayment.setPrincipleOverdraft(Double.parseDouble(paymentList.get(7)));
    			dhInsteadPayment.setInterestOverdraft(Double.parseDouble(paymentList.get(8)));
    			dhInsteadPayment.setAccreditTotal(Double.parseDouble(paymentList.get(9)));
    			dhInsteadPayment.setDateNumOverdue((int)Double.parseDouble(paymentList.get(10)));
    			dhInsteadPayment.setNumContinuous((int)Double.parseDouble(paymentList.get(11)));
    			dhInsteadPayment.setStage(paymentList.get(12));
    			listDhOverdue.add(dhInsteadPayment);
				if(i>=50) break;
			}
		}
		PageVo page = new PageVo();
		page.setRecords(1);
		page.setRows(listDhOverdue);
		return ApiResponse.success(page);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: save  <br/>
     * @Description: 新增 <br/>
     * @param dhInsteadPayment
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute DhInsteadPayment dhInsteadPayment) {
    	AbstractSysUser currentUser = getCurrentUser();
    	dhInsteadPayment.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	dhInsteadPayment.setModifierName(currentUser.getName());
        dhInsteadPaymentService.saveUpdateAndDelete(dhInsteadPayment, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: remove  <br/>
     * @Description: 删除<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	dhInsteadPaymentService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: disable  <br/>
     * @Description: 禁用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	dhInsteadPaymentService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: enable <br/>
     * @Description: 启用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	dhInsteadPaymentService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: modify  <br/>
     * @Description: 修改 <br/>
     * @param dhInsteadPayment
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute DhInsteadPayment dhInsteadPayment) {
    	AbstractSysUser currentUser = getCurrentUser();
    	dhInsteadPayment.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	dhInsteadPayment.setModifierName(currentUser.getName());
    	dhInsteadPaymentService.saveUpdateAndDelete(dhInsteadPayment, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询", response = DhInsteadPayment.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       DhInsteadPayment dhInsteadPayment = dhInsteadPaymentService.selectById(id);
       if(null == dhInsteadPayment) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(dhInsteadPayment);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: list  <br/>
     * @Description: 条件查询 <br/>
     * @param dhInsteadPaymentExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询",response = DhInsteadPayment.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute DhInsteadPaymentExt dhInsteadPaymentExt){
        dhInsteadPaymentExt.notDeleted();
        PageVo page = getPage(dhInsteadPaymentExt);
        int records = dhInsteadPaymentService.countByExt(dhInsteadPaymentExt);
        page.setRecords(records);
        if (records > 0) {
        	DhInsteadPaymentApply dhInsteadPaymentApply=null;
            List<DhInsteadPayment> dpBaseDataDictionaries = dhInsteadPaymentService.selectByExt(dhInsteadPaymentExt);
            for (DhInsteadPayment dhInsteadPayment : dpBaseDataDictionaries) {
            	dhInsteadPaymentApply=new DhInsteadPaymentApply();
            	dhInsteadPaymentApply.setBusiId(dhInsteadPayment.getBusiId());
            	dhInsteadPaymentApply.setDpStatus(DpStatus.NORMAL.getCode());
            	dhInsteadPaymentApply=dhInsteadPaymentApplyService.selectRefined(dhInsteadPaymentApply);
            	if(dhInsteadPaymentApply!=null){
            		dhInsteadPayment.setRemarks(dhInsteadPaymentApply.getRemarks());
            		dhInsteadPayment.setDateInstead(dhInsteadPaymentApply.getDateInstead());
            	}
			}
            page.setRows(dpBaseDataDictionaries);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

}
